package com.anxinr.service.impl;

import com.anxinr.mapper.UsersMapper;
import com.anxinr.pojo.entity.Users;
import com.anxinr.service.IUsersService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

/**
 * @author anxinr
 */
@Service
public class IUsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {
    @Override
    public HashMap<String, Object> login(Users users) throws Exception {
        try {
            HashMap<String, Object> map = new HashMap<>();
            String name = users.getName();
            String password = users.getPassword();
            LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Users::getName,name);
            Users one = this.getOne(wrapper);
            if (Objects.isNull(one)){
                throw new Exception("账号不能为空!") ;
            }
            if(name.equals(one.getName())){
                if (StringUtils.isNotBlank(password)){
                    if (password.equals(one.getPassword())){
                        map.put("token",one.getId());
                        return map;
                    }else {
                        throw new Exception("账号或密码错误!") ;
                    }
                }else {
                    throw new Exception("密码不能为空!") ;
                }
            }else {
                throw new Exception("账号错误或者用户重复!") ;
            }
        }catch (Exception e){
            e.printStackTrace();
            throw e ;
        }

    }

    @Override
    public Page<Users> queryUsers(Users users) {
        Page<Users> page = new Page<>(users.getPage(), users.getSize());
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(users.getName()),Users::getName,users.getName());
        wrapper.like(StringUtils.isNotBlank(users.getEmail()),Users::getEmail,users.getEmail());
        return this.page(page,wrapper);
    }
}
